import { useEffect, DependencyList, useRef, useCallback } from 'react'

export const useDebounce = (fn: Function, ms: number = 0, deps: DependencyList = []): [() => void, () => void] => {
	const timeout = useRef<ReturnType<typeof setTimeout>>()
	const callback = useRef(fn)

	const start = useCallback(() => {
		timeout.current && clearTimeout(timeout.current)

		timeout.current = setTimeout(() => {
			callback.current()
		}, ms)
	}, [ms])

	const clear = useCallback(() => {
		timeout.current && clearTimeout(timeout.current)
	}, [])

	useEffect(() => {
		callback.current = fn
	}, [fn])

	useEffect(() => {
		start()
		return clear
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [ms, ...deps])

	return [start, clear]
}
